package com.web.estate.interceptor;

import static com.web.estate.common.Constants.COOKIE_LOGIN_ID;

import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.UrlPathHelper;

import com.web.estate.common.UrlBroker;

public abstract class AbstractHandlerInterceptorAdapter extends HandlerInterceptorAdapter {

	private AntPathMatcher antPathMatcher = new AntPathMatcher();

	private UrlPathHelper urlPathHelper = new UrlPathHelper();

	@Value("${cookie.domain}")
	private String domain;

	protected boolean isLogin(HttpServletRequest req) {
		Cookie[] cookies = req.getCookies();
		if (ArrayUtils.isNotEmpty(cookies)) {
			for (Cookie cookie : cookies) {
				if (COOKIE_LOGIN_ID.equals(cookie.getName()) && StringUtils.isNotBlank(cookie.getValue())
						&& domain.equals(cookie.getDomain())) {
					return true;
				}
			}
		}

		return false;
	}

	public AbstractHandlerInterceptorAdapter() {
		urlPathHelper.setUrlDecode(false);
	}

	public void setAntPathMatcher(AntPathMatcher antPathMatcher) {
		this.antPathMatcher = antPathMatcher;
	}

	public void setUrlPathHelper(UrlPathHelper urlPathHelper) {
		this.urlPathHelper = urlPathHelper;
	}

	public abstract List<String> getFilterPaths();

	public boolean match(HttpServletRequest request) {
		List<String> filterPaths = getFilterPaths();
		for (String path : filterPaths) {
			if (matchHelp(path, request)) {
				return true;
			}
		}
		return false;
	}

	public boolean match(String url) {
		List<String> filterPaths = getFilterPaths();
		for (String path : filterPaths) {
			if (antPathMatcher.match(path, url)) {
				return true;
			}
		}
		return false;
	}

	private boolean matchHelp(String pattern, HttpServletRequest request) {
		return antPathMatcher.match(pattern, urlPathHelper.getLookupPathForRequest(request));
	}


	public String getGotoURL(HttpServletRequest request) {
		UrlBroker urlBroker = new UrlBroker(request.getRequestURI());
		for (Object keyObj : request.getParameterMap().keySet()) {
			String key = keyObj.toString();
			String value = request.getParameter(key);
			urlBroker.addQueryData(key, value);
		}
		return urlBroker.fork();
	}
}
